package com.imooc.miaosha.rabbitmq;

import com.imooc.miaosha.constant.MqConstant;
import com.imooc.miaosha.util.TypeConversionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.core.AmqpTemplate;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.MessageProperties;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * 模块描述: <br>
 * (生产者)
 *
 * @Author: Mr. xyb
 * @Date: 2019/4/24 13:18
 * @since: 1.8.0
 * @version: 1.0.0
 */
@Service
public class MqSender {

    Logger log = LoggerFactory.getLogger(MqSender.class);


    @Autowired
    private AmqpTemplate amqpTemplate;

    public void send(Object message) {
        String msg = TypeConversionUtils.beanToString(message);
        amqpTemplate.convertAndSend(MqConstant.QUEUE, msg);
    }

    public void topicSend(Object message) {
        String msg = TypeConversionUtils.beanToString(message);
        amqpTemplate.convertAndSend(MqConstant.TOPIC_CHANGE, MqConstant.ROUTING_KEY_1, msg + "key1");
        amqpTemplate.convertAndSend(MqConstant.TOPIC_CHANGE, "topic.key2", msg + "key2");

        amqpTemplate.convertAndSend(MqConstant.FANOUT_EXCHANGE, "", msg + "fanout");
    }

    public void sendHeader(Object message) {
        String msg = TypeConversionUtils.beanToString(message);
        log.info("send fanout message:" + msg);
        MessageProperties properties = new MessageProperties();
        properties.setHeader("header1", "value1");
        properties.setHeader("header2", "value2");
        Message obj = new Message(msg.getBytes(), properties);
        amqpTemplate.convertAndSend(MqConstant.HEADERS_EXCHANGE, "", obj);
    }

    /**
     * 发送秒杀请求
     *
     * @param mm
     */
    public void sendMiaoshaMessage(MiaoshaMessage mm) {
        String msg = TypeConversionUtils.beanToString(mm);
        log.info("send msg:" + msg);
        amqpTemplate.convertAndSend(MqConstant.MIAOSHA_QUEUE, msg);
    }
}
